package ua.diploma.whipup;

import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import ua.diploma.core.Constants;
import ua.diploma.core.ServiseFactory;
import ua.diploma.hibernate.dto.SecretQuestion;

/**
 * Контроллер подгрузки динамического содержимого
 * 
 * @author netstalk3r
 * 
 */
@WebServlet(name = "whipup", urlPatterns = { "/private/whipup" })
public class WhipUpController extends HttpServlet {

	private static final long serialVersionUID = 1L;

	private static final String ACTION_ERROR = "Неправильный запрос.";

	/**
	 * логгер
	 */
	private static final Logger log = Logger.getLogger(WhipUpController.class);

	/**
	 * контсруктор по умолчанию
	 */
	public WhipUpController() {
		super();
	}

	protected void service(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		final String action = request.getParameter(Constants.ACTION_PARAM);
		log.info("WhipUpController, action = " + action);
		if (action == null) {
			List<String> secretQuestionsText = new ArrayList<String>();
			secretQuestionsText.add(ACTION_ERROR);
			request.setAttribute("questions", secretQuestionsText);
			request.getRequestDispatcher(Constants.VALID_JSON_QUESTIONS_VIEW)
					.forward(request, response);
			return;
		} else if (action.equals("loadSecretQuestions")) {
			WhipUpService loader = ServiseFactory.getWhipUpService();
			List<String> secretQuestionsText = new ArrayList<String>();
			try {
				List<SecretQuestion> secretQuestions = loader
						.loadSecretQuestions();
				for (SecretQuestion question : secretQuestions) {
					secretQuestionsText.add(question.getQuestion());
				}
			} catch (SQLException e) {
				log.error("Ошибка работы с БД", e);
				secretQuestionsText.add("Ошибка работы с Базой Данных.");
			}
			request.setAttribute("questions", secretQuestionsText);
			request.getRequestDispatcher(Constants.VALID_JSON_QUESTIONS_VIEW)
					.forward(request, response);
			return;
		}
	}

}
